package com.sicheng.algorithm.array;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author zsc
 * @version 1.0
 * @date 2021/9/17 9:13
 */
public class MergeArr {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(merge(new int[]{1, 4, 5, 7, 9, 11, 19}, new int[]{-9, 2, 5, 7, 8, 10})));
    }

    public static int[] merge(int[] arr1, int[] arr2) {
        if (arr1 == null || arr2 == null || arr1.length == 0 || arr2.length == 0)
            return null;

        // list.size()=0,
        // 即不会一开始就开辟存放大数组的空间
        ArrayList<Integer> list = new ArrayList<>();
        //以arr1为参照，合并arr2
        int left = 0, right = 0;
        while (left < arr1.length && right < arr2.length) {
            if (arr1[left] <= arr2[right]) {
                list.add(arr1[left++]);
            } else
                list.add(arr2[right++]);
        }

        while (left < arr1.length)
            list.add(arr1[left++]);

        while (right < arr2.length)
            list.add(arr2[right++]);

        return list.stream().mapToInt(e -> e).toArray();

    }
}
